<?php

namespace app\common\tool;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Excel
{
    /**
     * 导入Excel表取出需要的内容
     * @param $excelPath    excel表路径
     * @param $param    每列对应数据键名及标题 ['A' => ['key' => 'A',title => '标题名称']] 标题名为空则不验证
     * @param $startRow 内容开始的行
     * @return array    返回数据内容 [['A' => 'content']];
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \think\Exception
     */
    function importExcel($param, $startRow=2)
    {
        try {
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return ['code'=>-1,'msg'=>'文件大小不能超过5M'];
                //$this->error('文件大小不能超过5M');
                //exit();
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xls' && $fileExtendName != 'xlsx') {
                return ['code'=>-1,'msg'=>'必须为excel表格，且必须为xls或xlsx格式！'];
                /*$this->error('必须为excel表格，且必须为xls格式！');
                exit();*/
            }
            $excelPath = $_FILES['file']['tmp_name'];
            $excelObj = IOFactory::load($excelPath);
            $excelWorkSheet = $excelObj->getActiveSheet();
            $rowCount = $excelWorkSheet->getHighestRow();
            if ($rowCount <= 0) {
                return ['code'=>-1,'msg'=>'请检查模板标题是否正确~'];
            }
            //var_dump($param);exit;
            //验证标题
            /*foreach ($param as $column => $content) {
                $item = $excelWorkSheet->getCell($column . ($startRow-1))->getCalculatedValue();
                if ($item != $content['title'] && !empty($content['title'])) {
                    return ['code'=>-1,'msg'=>'请检查模板标题是否正确~~'];
                }
            }*/
            $excelData = array();
            for ($row = $startRow; $row <= $rowCount; $row++ ) {
                $rowData = array();
                foreach ($param as $column => $content) {
                    $item = $excelWorkSheet->getCell($column . $row)->getCalculatedValue();
                    $rowData[$content['key']] = $item;
                }
                if(!implode('',$rowData)){
                    continue;//删除空行
                }
                $excelData[] = $rowData;
            }

            return $excelData;
        }catch (\Exception $e){
            halt($e->getMessage());
            return ['code'=>-1,'msg'=>$e->getMessage()];
        }

    }

}